package com.foreknow.service.impl;

import com.foreknow.dao.impl.AdminDaoImpl;
import com.foreknow.dao.impl.GuestbookDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookServiceImpl implements GuestbookService {
    @Override
    public boolean addGuestbook(Guestbook gb) {
        //1. 连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //2. 注入数据库的连接
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        guestbookDao.setConnection(conn);
        boolean isRight = false;
        //事务的处理
        try {
            isRight = guestbookDao.save(gb);
            conn.commit();//提交事务
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return isRight;
    }

    @Override
    public List<Guestbook> getQueryAll() {
        //1. 连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //2. 注入数据库的连接
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        guestbookDao.setConnection(conn);
        return guestbookDao.getAllMessage();
    }

    @Override
    public boolean deleteById(int id) {
        //1. 连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //2. 注入数据库的连接
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        guestbookDao.setConnection(conn);
        boolean isRight = false;
        //事务的处理
        try {
            isRight = guestbookDao.deleteById(id);
            conn.commit();//提交事务
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return isRight;
    }
}
